import 'package:bazi/util/lunraToSolar.dart';
import 'package:bazi/util/paipan.dart';
import 'package:bazi/util/solarToLunar.dart';
import 'package:bazi/util/my_color.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';


class CalendarWidget extends StatefulWidget {
  late CalendarCallBack confirm;
  late int year;
  late int month;
  late int day;
  late bool showHour;
  CalendarWidget(int year, int month,int day, CalendarCallBack confirm,{bool showHour = false}){
    this.confirm = confirm;
    this.year = year;
    this.month = month;
    this.day = day;
    this.showHour = showHour;
  }
  @override
  _CalendarWidgetState createState() => _CalendarWidgetState();
}

class _CalendarWidgetState extends State<CalendarWidget> {
  late CalendarCallBack _confirm;
  late SolarToLunar _lunar;
  List<int> _yearList = [];
  List<int> _monthList = [];
  List<int> _dayList = [];
  //农历月日
  List<String> _lunarMonthList = List.from(SolarToLunar.chineseNumber);
  List<String> _lunarDayList = [];
  String _lunraDate='';
  bool _isLunar = false;
  int h = 44;
  int _year=0;
  int _month = 0;
  int _day = 0;
  int _hour = 2;
  int _dateCount = 0;
  int _lunarDateCount = 0;
  late ScrollController _yearController;
  late ScrollController _monthController;
  late ScrollController _dayController;
  late ScrollController _hourController;
  List<String> _hourValue =[
    "","",
    "子时 00点","丑时 01点","丑时 02点","寅时 03点","寅时 04点","卯时 05点",
    "卯时 06点","辰时 07点","辰时 08点","巳时 09点","巳时 10点","午时 11点","午时 12点","未时 13点","未时 14点",
    "申时 15点","申时 16点","酉时 17点","酉时 18点","戌时 19点","戌时 20点","亥时 21点","亥时 22点","子时 23点",
    "",""
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _confirm = widget.confirm;
    //初始化农历时间
    _lunar = SolarToLunar(DateTime(widget.year,widget.month,widget.day));
    _lunarDateCount = SolarToLunar.monthDays(widget.year, widget.month);
    _lunraDate = "农历：${_lunar.year}年${_lunarMonthList[_lunar.month-1]}月${SolarToLunar.getChinaDayString(_lunar.day)}";
    for(int i = -1;i<_lunarDateCount+4;i++){
      if(i<1||i>_dateCount+2){
        _lunarDayList.add("");
      }else{
        _lunarDayList.add(SolarToLunar.getChinaDayString(i));
      }

    }
    _lunarMonthList.add("");
    _lunarMonthList.add("");
    _lunarMonthList.insert(0, "");
    _lunarMonthList.insert(0, "");
    //初始化公历时间
    _dateCount = DateTime(widget.year,widget.month+1,0).day;
    for(int i = 1898;i<2052;i++){
      _yearList.add(i);
    }

    for(int i =-1;i<15;i++){

        _monthList.add(i);

    }
    _month =_monthList.indexOf( widget.month);
    for(int i=-1;i<_dateCount+3;i++){
      _dayList.add(i);
    }

    //初始化日历位置
  _yearController = ScrollController(initialScrollOffset: h*((_yearList.indexOf(widget.year)-2).toDouble()));
    _monthController = ScrollController(initialScrollOffset: h*((_monthList.indexOf(widget.month)-2).toDouble()));
    _dayController = ScrollController(initialScrollOffset: h*((_dayList.indexOf(widget.day)-2).toDouble()));
    _hourController = ScrollController();

    _year = _yearList.indexOf(widget.year);
    _month = _monthList.indexOf(widget.month);
    _day = _dayList.indexOf(widget.day);
    //年视图滑动监听
  _yearController.addListener(() {
      if(_yearController.offset%h>39){
        _year = ((_yearController.offset/h)+3).toInt();
      }else{
        _year = ((_yearController.offset/h)+2).toInt();
      }
    setState(() {
    });
  });
    //月视图滑动监听
    _monthController.addListener(() {
      if(_monthController.offset%h>39){
        _month = ((_monthController.offset/h)+3).toInt();
      }else{
        _month = ((_monthController.offset/h)+2).toInt();
      }

      _dateCount = DateTime(_yearList[_year],_monthList[_month]+1,0).day;
      _dayList.clear();
      for(int i=-1;i<_dateCount+3;i++){
        _dayList.add(i);
      }
      setState(() {

      });
    });

    //日视图滑动监听
    _dayController.addListener(() {
      if(_dayController.offset%h>39 ){
        _day = ((_dayController.offset/h)+3).toInt();
      }else{
        _day = ((_dayController.offset/h)+2).toInt();
      }
      setState(() {

      });
    });

    //时间视图滑动监听
    _hourController.addListener(() {
      if(_hourController.offset%h>39 ){
        _hour = ((_hourController.offset/h)+3).toInt();
      }else{
        _hour = ((_hourController.offset/h)+2).toInt();
      }
      setState(() {

      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Container(
          color: Colors.white.withOpacity(0.94),
          height: 300,
          width: ScreenUtil.getScreenW(context),
          child: Column(children: [
            SizedBox(height: 10,),
            Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [

            GestureDetector(
              onTap: _tapLunarToSolar,
              child: Container(
                width: 70,
                height: 30,
                decoration: BoxDecoration(border:Border.all(color:MyColor.primaryColor),color:_isLunar? Colors.white:MyColor.primaryColor ),
                alignment: Alignment.center,
                child: Text("公历",style: TextStyle(color: _isLunar?MyColor.primaryColor:Colors.white),),),
            ),
              GestureDetector(
                onTap: _tapSolarToLunar,
                child: Container(
                  width: 70,
                  height: 30,
                  decoration: BoxDecoration(border:Border.all(color:MyColor.primaryColor),color:_isLunar?MyColor.primaryColor :Colors.white ),
                  alignment: Alignment.center,
                  child: Text("农历",style: TextStyle(color:_isLunar? Colors.white:MyColor.primaryColor),),),
              ),
          ],),
            Expanded(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                width: double.infinity,
                child: Row(
                  children: [
                    //年
                   Container(
                     width:80,
                     child: ListView.builder(itemBuilder: (context,index){
                       return Container(
                         alignment: Alignment.center,
                           height:h.toDouble(),
                           child: Text(index<152&&index>1?_yearList[index].toString()+"年":"",style: TextStyle(
                             color: _year==index?MyColor.primaryColor:Colors.black54,
                             fontSize: 20
                           ),));
                     },itemCount: _yearList.length,controller: _yearController,),
                   ),
                    //月
                    Expanded(
                        child: ListView.builder(itemBuilder: (context,index){

                          return Container(
                              alignment: Alignment.center,
                              height:h.toDouble(),
                              child: Text(_isLunar?index<14&&index>1?_lunarMonthList[index]+"月":_lunarMonthList[index]:index<14&&index>1?_monthList[index].toString()+"月":"",style: TextStyle(
                                  color: _month==index?MyColor.primaryColor:Colors.black54,
                                  fontSize: 20
                              ),));
                        },itemCount: _monthList.length,controller: _monthController)
                    ),
                    //日
                    widget.showHour?Expanded(
                        child: ListView.builder(itemBuilder: (context,index){
                          return Container(
                              alignment: Alignment.center,
                              height:h.toDouble(),
                              child: Text(_isLunar?_lunarDayList[index]:index>1&&index<_dateCount+2?_dayList[index].toString():"",style: TextStyle(
                                  color: _day==index?MyColor.primaryColor:Colors.black54,
                                  fontSize: 20
                              ),));
                        },itemCount:_isLunar? _lunarDayList.length:_dayList.length,controller: _dayController)
                    ):Container(
                      width: 50,
                      child: ListView.builder(itemBuilder: (context,index){
                        return Container(
                            alignment: Alignment.center,
                            height:h.toDouble(),
                            child: Text(_isLunar?_lunarDayList[index]:index>1&&index<_dateCount+2?_dayList[index].toString():"",style: TextStyle(
                                color: _day==index?MyColor.primaryColor:Colors.black54,
                                fontSize: 20
                            ),));
                      },itemCount:_isLunar? _lunarDayList.length:_dayList.length,controller: _dayController),
                    ),
                    //时
                   widget.showHour? Container(
                     width: 100,
                     child: ListView.builder(itemBuilder: (context,index){
                       return Container(
                           alignment: Alignment.center,
                           height:h.toDouble(),
                           child: Text(_hourValue[index],style: TextStyle(
                               color: _hour==index?MyColor.primaryColor:Colors.black54,
                               fontSize: 20
                           ),));
                     },itemCount:_hourValue.length,controller: _hourController),
                   ):Container(),
                  ],
                )
              ),
            ),
            //确定，取消
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: (){Navigator.pop(context);},
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(color: Colors.white,
                          border: Border.symmetric(horizontal: BorderSide(color: Colors.black12))
                      ),
                      height: 50,
                      child: Text("取消",),
                    ),
                  ),
                ),
                Container(
                  width: 1,
                  height: 50,
                  color: Colors.black12,
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: (){

                      if(_isLunar){
                        /// 农历
                        List<int> solar = LunarToSolar.lunarToSolar(_yearList[_year],_monthList[_month], _dayList[_day], false);
                        print(solar);
                        print(_day);
                        _lunraDate = "农历:${_yearList[_year]}年${_lunarMonthList[_month]}月${SolarToLunar.getChinaDayString(_day-1)}";
                        if(widget.showHour){
                          String hourValue = '';
                          int hour = 0;
                          switch(_hour){
                            case 2:
                              hour = 0;
                              hourValue = "子时";
                              break;
                            case 25:
                              hour = 12;
                              hourValue = "子时";
                              break;
                            case 3:
                            case 4:
                              hour = 1;
                              hourValue = "丑时";
                              break;
                            case 5:
                            case 6:
                            hour = 2;
                              hourValue = "寅时";
                              break;
                            case 7:
                            case 8:
                            hour = 3;
                              hourValue = "卯时";
                              break;
                            case 9:
                            case 10:
                            hour = 4;
                              hourValue = "辰时";
                              break;
                            case 11:
                            case 12:
                            hour = 5;
                              hourValue = "巳时";
                              break;
                            case 13:
                            case 14:
                            hour = 6;
                              hourValue = "午时";
                              break;
                            case 15:
                            case 16:
                            hour = 7;
                              hourValue = "未时";
                              break;
                            case 17:
                            case 18:
                            hour = 8;
                              hourValue = "申时";
                              break;
                            case 19:
                            case 20:
                            hour = 9;
                              hourValue = "酉时";
                              break;
                            case 21:
                            case 22:
                            hour = 10;
                              hourValue = "戌时";
                              break;
                            case 23:
                            case 24:
                            hour = 11;
                              hourValue = "酉时";
                              break;
                          }
                          _lunraDate = _lunraDate+" "+hourValue;
                          _confirm(solar[0],solar[1],solar[2],"公历:${solar[0]}年${solar[1]}月${solar[2]}日",
                              _lunraDate,_isLunar, hour
                          );
                        }else{
                          _confirm(solar[0],solar[1],solar[2],"公历:${solar[0]}年${solar[1]}月${solar[2]}日",
                              _lunraDate,_isLunar,14
                          );
                        }

                      }else {
                        ///公历
                        DateTime dateTime = DateTime(_yearList[_year],_monthList[_month],_dayList[_day]);
                        _lunar = SolarToLunar(dateTime);
                        String date = "公历:${_yearList[_year]}年${_monthList[_month]}月${_dayList[_day]}日";
                        _lunraDate = "农历:${_lunar.year}年${_lunarMonthList[_lunar.month+1]}月${SolarToLunar.getChinaDayString(_lunar.day)}";
                        if(widget.showHour){
                          String hourValue = '';
                          int hour =0;
                          switch(_hour){
                            case 2:
                              hour = 0;
                              hourValue = "00点";
                              break;
                            case 25:
                              hour = 12;
                              hourValue = "23点";
                              break;
                            case 3:
                              hour = 1;
                              hourValue = "01点";
                              break;
                            case 4:
                              hour = 1;
                              hourValue = "02点";
                              break;
                            case 5:
                              hour = 2;
                              hourValue = "03点";
                              break;
                            case 6:
                              hour = 2;
                              hourValue = "04点";
                              break;
                            case 7:
                              hour = 3;
                              hourValue = "05点";
                              break;
                            case 8:
                              hour = 3;
                              hourValue = "06点";
                              break;
                            case 9:
                              hour = 4;
                              hourValue = "07点";
                              break;
                            case 10:
                              hour = 4;
                              hourValue = "08点";
                              break;
                            case 11:
                              hour = 5;
                              hourValue = "09点";
                              break;
                            case 12:
                              hour = 5;
                              hourValue = "10点";
                              break;
                            case 13:
                              hour = 6;
                              hourValue = "11点";
                              break;
                            case 14:
                              hour = 6;
                              hourValue = "12点";
                              break;
                            case 15:
                              hour = 7;
                              hourValue = "13点";
                              break;
                            case 16:
                              hour = 7;
                              hourValue = "14点";
                              break;
                            case 17:
                              hour = 8;
                              hourValue = "15点";
                              break;
                            case 18:
                              hour = 8;
                              hourValue = "16点";
                              break;
                            case 19:
                              hour = 9;
                              hourValue = "17点";
                              break;
                            case 20:
                              hour = 9;
                              hourValue = "18点";
                              break;
                            case 21:
                              hour = 10;
                              hourValue = "19点";
                              break;
                            case 22:
                              hour = 10;
                              hourValue = "20点";
                              break;
                            case 23:
                              hour = 11;
                              hourValue = "21点";
                              break;
                            case 24:
                              hour = 11;
                              hourValue = "22点";
                              break;
                          }
                          date = date+" "+hourValue;
                          _confirm(_yearList[_year], _monthList[_month],
                              _dayList[_day],
                              date,
                              _lunraDate,
                              _isLunar,
                               hour
                          );
                        }else{
                          _confirm(_yearList[_year], _monthList[_month],
                              _dayList[_day],
                              date,
                              _lunraDate,
                              _isLunar,
                            14
                          );
                        }


                      }
                      Navigator.pop(context);
                    },
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(color: Colors.white,
                          border: Border.symmetric(horizontal: BorderSide(color: Colors.black12))
                      ),

                      height: 50,
                      child: Text("确定",style: TextStyle(color: MyColor.primaryColor),),
                    ),
                  ),
                )
              ],
            )
          ],),
        ),
      ),
    );
  }

  void _tapLunarToSolar(){
    _isLunar  = false;

    List<int> solar = LunarToSolar.lunarToSolar(_yearList[_year],_monthList[_month], _dayList[_day], false);

    _yearController.jumpTo(((_yearList.indexOf(solar[0]-2)*h).toDouble()));
    _monthController.jumpTo(((_monthList.indexOf(solar[1])-2)*h).toDouble());
    _dayController.jumpTo(((_dayList.indexOf(solar[2])-2)*h).toDouble());
    _dateCount = DateTime(_yearList[_year],_monthList[_month]+1,0).day;
    _dayList.clear();
    for(int i=-1;i<_dateCount+3;i++){
    _dayList.add(i);
    }
    setState(() {

    });
  }
  void _tapSolarToLunar(){
    _isLunar = true;
    DateTime dateTime = DateTime(_yearList[_year],_monthList[_month],_dayList[_day]);
    _lunarDateCount = SolarToLunar.monthDays(dateTime.year, dateTime.month);
    _lunar = SolarToLunar(dateTime);
    _yearController.jumpTo(((_yearList.indexOf(_lunar.year)-2)*h).toDouble());
    _monthController.jumpTo(((_monthList.indexOf(_lunar.month)-2)*h).toDouble());
    _dayController.jumpTo(((_dayList.indexOf(_lunar.day)-2)*h).toDouble());
    _lunarDayList.clear();
    for(int i = -1;i<_lunarDateCount+4;i++){
      if(i<1||i>_lunarDateCount+2){
        _lunarDayList.add("");
      }else{
        _lunarDayList.add(SolarToLunar.getChinaDayString(i));
      }

    }
    print(_lunarDayList);
    setState(() {

    });
  }
}
 typedef CalendarCallBack =void Function (int year,int month,int day,String date,String lunarDate,bool isLunar,int hour);

